import com.google.gson.Gson;
import mysql.DBTool;
import pojo.Book;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author DASK
 * @date 2020/4/2 14:54
 * @description //TODO 查询动作拦截器
 */
public class SearchServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] path = req.getRequestURL().toString().split("/");
        resp.setContentType("application/json; charset=utf-8");// 指定返回的格式为JSON格式
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        Gson gson = new Gson();
        String content = req.getParameter("text");
        switch (path[path.length - 1]) {
            case "byBookName":
                List<Book> books = DBTool.searchBookByName(content);
                writer.write(gson.toJson(books));
                break;
            case "byAuthor":
                List<Book> books1 = DBTool.searchBooksByAuthor(content);
                writer.write(gson.toJson(books1));
                break;
        }
        writer.flush();
        writer.close();
    }
}
